<?php
App::import("Vendor","Cms.ModelCacheStore");
class SystemModelCache extends AppModel implements ModelCacheStore
{
	var $name = "SystemModelCache";
	var $table = "system_model_cache";
	var $useTable = "system_model_cache";
	var $recentRecords = array();
	var $recentRecordsCount = 0;
	function writeCache($modelAlias,$entityId,$field,$value,$duration)
	{
		$id = $this->field("id",array("entity" => $modelAlias,
							"cache_key" => $field,
						"entity_id" => $entityId));
		$data = array(
			"entity" => $modelAlias,
			"entity_id" => $entityId,
			"cache_key" => $field,
			"value" => serialize($value),
			"expires"=> strtotime($duration)
		);
		$this->create();
		$this->id = $id;
		$this->save(array(
			$this->alias => $data
		));
	}
	
	function getCacheValues($modelAlias,$cacheFields,$resultIds)
	{
		$time = time();
		if(count($resultIds) == 1)
		{
			$resultIds = array_pop($resultIds);
		}
		if(is_numeric($resultIds))
		{
			if(isset($this->recentRecords[$modelAlias][$resultIds]))
			{
				return array(
					$resultIds => $this->recentRecords[$modelAlias][$resultIds]
				);
			}
		}
		$caches = $this->find("all",array("callbacks"=>false,"conditions"=>array(
			"entity" => $modelAlias,
			"cache_key" => $cacheFields,
			"entity_id" => $resultIds,
			"expires >" => $time
		),"recursive"=>-1));
		foreach($caches as $key => $cache)
		{
			$cache[$this->alias]['value'] = unserialize($cache[$this->alias]['value']);
			unset($cache[$this->alias]['expires'],$cache[$this->alias]['entity'],$cache[$this->alias]['expires']);
			$caches[$key] = $cache;
			if(count($resultIds) == 1 || is_numeric($resultIds))
			{
				if($this->recentRecordsCount > 15)
				{
					$this->recentRecordsCount = array();
				}
				$this->recentRecords[$modelAlias][$cache[$this->alias]['entity_id']][$cache[$this->alias]['cache_key']] = $cache[$this->alias]['value'];
				$this->recentRecordsCount++;
			}
		}
		$caches = Set::combine($caches,"{n}.SystemModelCache.cache_key","{n}.SystemModelCache.value","{n}.SystemModelCache.entity_id");
		return $caches;
	}
	
	function deleteCache($modelAlias,$fields,$modelIds)
	{
		$this->deleteAll(array("entity"=>$modelAlias,"entity_id"=>$modelIds,"cache_key"=>$fields));
	}
}
